package com.example.demo.filter;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.demo.pojo.JsonResult;
import com.example.demo.pojo.security.UserSecurity;
import com.example.demo.util.JwtUtil;

import com.example.demo.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *
 * security
 * @author 1
 */
@Component
public class JwtFilter extends OncePerRequestFilter {
    private final Logger logger= LoggerFactory.getLogger(JwtFilter.class);
    @Resource
    private RedisUtil redisUtil;


    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        String url = httpServletRequest.getRequestURI();

        //
        if (url.contains("/save")|| url.contains("/login")){
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        String authorization = httpServletRequest.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)){
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        UserSecurity userSecurity = null;
        //获取认证信息
        try {
            String uuid = JwtUtil.verifyToken(authorization);
            System.out.println("uuid = " + uuid);
            userSecurity= (UserSecurity) redisUtil.get(uuid);
        } catch (Exception e) {
            JsonResult<Object> jsonResult = new JsonResult<>("401", "用户认证失败!请重新登录");
            String fileName = JSONUtil.toJsonStr(jsonResult);
            httpServletResponse.setCharacterEncoding("utf-8");
            httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
            httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
            PrintWriter writer = httpServletResponse.getWriter();
            writer.println(fileName);
            writer.flush();
            writer.close();
            e.printStackTrace();
        }
        UsernamePasswordAuthenticationToken tokenLogin = new UsernamePasswordAuthenticationToken(userSecurity, null, userSecurity.getSimpleGrantedAuthority());

        //存入用户信息
        SecurityContextHolder.getContext().setAuthentication(tokenLogin);

        filterChain.doFilter(httpServletRequest, httpServletResponse);




    }


//    @Override
//    public void init(FilterConfig filterConfig) throws ServletException {
//        System.out.println("222222222222222222222222222");
//        Filter.super.init(filterConfig);
//    }
//
//    @Override
//    public void doFilter(ServletRequest servletRequest,  ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        HttpServletRequest request=(HttpServletRequest)servletRequest;
//        HttpServletResponse response=(HttpServletResponse)servletResponse;
//
//        String uri=request.getRequestURI();
//        System.out.println("测试+"+uri);
//
//        //设置跨域请求
////        该字段必需。设置允许请求的域名，多个域名以逗号分隔，也可以设置成 * 即允许所有源访问
////        Access-Control-Allow-Origin:  http://www.YOURDOMAIN.com
////        该字段必需。设置允许请求的方法，多个方法以逗号分隔
////        Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
////        该字段可选。设置允许请求自定义的请求头字段，多个字段以逗号分隔
////        Access-Control-Allow-Headers: Authorization
////        该字段可选。设置是否允许发送 Cookies
////        Access-Control-Allow-Credentials: true
//
//        response.setCharacterEncoding("UTF-8");
//        //shiro默认是使用的cookie来实现的登录认证，
//        // 这意味着我们前后端分离的项目需要设置Access-Control-Allow-Credentials为true，
//        // 并且前端ajax需要设置携带cookie请求。
//        // 也就是axios.defaults.withCredentials=true，才行。
//        // 我们这里由于使用token方式，所以我们的Access-Control-Allow-Credentials设置为false，这意味着我们的每个请求都是不同的请求会话。
//
//        //跟下一行配对出现,可带cookie
////        response.setHeader("Access-Control-Allow-Credentials", "true");
////        //不能使用*,设置允许的访问域,动态设置
////        //Access-Control-Allow-Credentials  是true的时候。
////        //Access-Control-Allow-Origin"的值不能为*。不可设置Access-Control-Allow-Origin
//        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
////        System.out.println(request.getHeader("Origin")+"请求");
////        System.out.println(request.getSession().getId()+"会话");
////        response.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE");
////        //设置可以跨域的请求头
//        response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
////        if (uri.contains("/user/login")||("OPTIONS").equals(request.getMethod())||uri.contains("/getRole")||uri.contains("/webSocket")||uri.contains("/favicon.ico")){
////            System.out.println("11111111111111111111111111111111111方法"+request.getMethod());
////            filterChain.doFilter(request, response);
////            return;
////        }
//
////        //获得token
////        String token=request.getHeader("Authorization");
////        //System.out.println(header.forEach((k,v)-> System.out.println(k+""+v)));
////            if (token==null){
////                //无token,跳转登录页
////                System.out.println("没token"+request.getMethod());
////                return;
////            }
////
////        Map<String, Claim> userData = JwtUtil.verifyToken(token);
////        if (userData.isEmpty()){
////            //无token,跳转登录页
////            System.out.println("token空空....."+request.getMethod());
////            return;
////        }
////        String userName= userData.get("userName").asString();
//        //放入request
//
//        filterChain.doFilter(request, response);
//        System.out.println("");
//    }
//
//    @Override
//    public void destroy() {
//        Filter.super.destroy();
//    }

}
